package ua.net.gm.server;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import ua.net.gm.common.matter.MatterId;
import ua.net.gm.server.player.PlayerId;
import ua.net.gm.server.world.Field;
import ua.net.gm.server.world.World;
import ua.net.gm.server.world.WorldBuilder;
import ua.net.gm.server.world.WorldId;
import ua.net.gm.server.world.WorldPlan;

public class WorldView extends Applet
{
   private static final long serialVersionUID = -1911939157148829815L;

    private final Color[] colors = new Color[]
    {
        Color.GREEN, Color.BLUE, Color.GRAY
    };

    WorldBuilder builder;
    ServerEntitySupport support;
    World world;
    
    public WorldView() throws HeadlessException
    {
        support = new ServerEntitySupport();
        MatterId.init(support);
        WorldId.init(support);
        PlayerId.init(support);

        support.getMatterDict().addEntity("Dirt");
        support.getMatterDict().addEntity("Water");
        support.getMatterDict().addEntity("Stone");
        
        builder = new WorldBuilder(support);
        
        WorldPlan plan = new WorldPlan();
        plan.setLabel("Test");
        plan.setAreaMatter("Dirt");
        plan.setWidth(256);
        plan.setHeight(256);
        plan.setBorderMatter("Stone");
        world = builder.create(plan);               
    }

    @Override
    public void paint(Graphics g)
    {
        super.paint(g);
        
        int scale = 2;
        for (int y = 0; y < world.getSize().getHeight(); y++)
        {
            for (int x = 0; x < world.getSize().getWidth(); x++)
            {
                Field f = world.getField(x, y);
                int matterId = f.getBottom().getId();
                g.setColor(colors[matterId]);
                g.fillRect(x * scale, y * scale, scale, scale);
            }
        }
    }

    public void init()
    {
        super.init();

        addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                repaint();
            }
        });
    }

    public static void main(String[] args)
    {

        Frame f = new Frame("Fractal Coastlines");
        f.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });

        f.setSize(600, 600);
        f.setLayout(new BorderLayout());
        WorldView q = new WorldView();
        q.init();
        f.add(q);

        f.setVisible(true);
    }
}
